package com.eim.taskgateway.config;

import com.eim.user.utils.api.ApiResponse;
import com.eim.user.utils.api.ApiResponseUtil;
import com.eim.user.utils.TokenUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 作为jwt过滤
 */
@Component
public class JwtTokenFilter implements GlobalFilter, Ordered {


    private static Logger logger= LoggerFactory.getLogger(JwtTokenFilter.class);


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取token
        String token = exchange.getRequest().getHeaders().getFirst("token");
        String url = exchange.getRequest().getURI().getPath();
        //忽略以下url请求
        if(url.indexOf("/user-service/login.do") >= 0){
            return chain.filter(exchange);
        }
        ServerHttpResponse response = exchange.getResponse();
        if(StringUtils.isBlank(token)){
            //没有token
            logger.error("没有token");
            return authErro(response,"请登录");
        }else{
            //有token
            boolean verify = TokenUtil.verify(token);
            if(!verify){
                logger.error("token过期");
                return authErro(response,"请重新登录");
            }
            return chain.filter(exchange);
        }
    }
    /**
     * 认证错误输出
     * @param resp 响应对象
     * @param mess 错误信息
     * @return
     */
    private Mono<Void> authErro(ServerHttpResponse resp,String mess) {
        resp.setStatusCode(HttpStatus.OK);
        resp.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        ApiResponse res= ApiResponseUtil.getApiResponse(405,mess);
        byte[] responseByte = JSONObject.fromObject(res).toString().getBytes(StandardCharsets.UTF_8);

        DataBuffer buffer = resp.bufferFactory().wrap(responseByte);
        return resp.writeWith(Flux.just(buffer));
    }
    @Override
    public int getOrder() {
        return -100;
    }
}
